# pragma once

# include "cpp_tools_Headers.h"

namespace cpp_tools
{
    template <typename Derived>
    Eigen::VectorXd cumtrapz(const Eigen::MatrixBase<Derived>& y, const Eigen::VectorXd& x = Eigen::VectorXd()) {
        // 检查输入
        if (y.size() == 0) {
            throw std::invalid_argument("Input array 'y' must not be empty.");
        }
        if (x.size() > 0 && x.size() != y.size()) {
            throw std::invalid_argument("Arrays 'x' and 'y' must have the same size.");
        }

        // 如果没有提供x，则默认为等间距的索引
        Eigen::VectorXd dx;
        if (x.size() == 0) {
            dx = Eigen::VectorXd::Ones(y.size() - 1);
        } else {
            dx = x.segment(1, x.size() - 1) - x.segment(0, x.size() - 1);
        }

        // 计算累积梯形积分
        Eigen::VectorXd result(y.size());
        result.setZero();
        for (int i = 1; i < y.size(); ++i) {
            result(i) = result(i - 1) + 0.5 * dx(i - 1) * (y(i) + y(i - 1));
        }

        return result;
    }
} // namespace cpp_tools
